package org.equinoxosgi.toast.internal.dev.airbag.fake;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.equinoxosgi.toast.dev.airbag.IAirbag;
import org.equinoxosgi.toast.dev.airbag.IAirbagListenser;

public class FakeAirbag implements IAirbag {
	private final List<IAirbagListenser> listeners;
	private Job job;
	private boolean isRunning;

	public FakeAirbag() {
		listeners = new ArrayList<>();
	}

	@Override
	public void addListener(final IAirbagListenser listener) {
		listeners.add(listener);
	}

	@Override
	public synchronized void deploy() {
		for (final IAirbagListenser listener : listeners) {
			listener.deployed();
		}
	}

	@Override
	public synchronized void removeListener(final IAirbagListenser listener) {
		listeners.remove(listener);
	}

	public synchronized void shutdown() {
		isRunning = false;
		job.cancel();
		try {
			job.join();
		} catch (final Exception e) {
		}
	}

	public synchronized void startup() {
		isRunning = true;
		job = new Job("FakeAirbag") {

			@Override
			protected IStatus run(final IProgressMonitor monitor) {
				deploy();
				if (isRunning) {
					schedule(5000);
				}
				return Status.OK_STATUS;
			}
		};
		job.schedule(5000);
	}
}
